package club.smatdot.api;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class RibbonController {
	
	@Autowired
	private DiscoveryClient discoveryClient;
	
	
	@Autowired
	private RestTemplate restTemplate;
	
	// 接口的请求总数
	private AtomicInteger requsetCount = new AtomicInteger(0);
	
	// 纯手写本地负载均衡
	public String ribbonMember() {
		String url = ribbonRemoteAddress() + "/getMember";
		return restTemplate.getForObject(url, String.class);
	}
	
	
	public String ribbonRemoteAddress() {
		// 1. 获取注册中心上远程调用地址
		List<ServiceInstance> serviceInstances = discoveryClient.getInstances("app-member");
		
		if(serviceInstances == null || serviceInstances.size() <= 0) {
			return null;
		}
		// 获取服务器集群个数
		int machineNumber = serviceInstances.size();
		int machineServer = 1 % machineNumber;
		requsetCount.incrementAndGet();
		return  serviceInstances.get(machineServer).getUri().toString();
	}
}
